<template>
  <div class="app-container">
      <!-- 站点基础配置 -->
      <el-card shadow="never" style="margin-bottom: 16px;">
        <div slot="header">站点基础配置</div>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px" label-position="left">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="网站标题" prop="webTitle">
              <el-input v-model="form.webTitle" placeholder="请输入网站标题"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="ICP备案号" prop="icp">
              <el-input v-model="form.icp" placeholder="请输入ICP备案号"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入联系邮箱"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="联系地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入联系地址"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="网站Logo" prop="webLogoFileId">
              <el-upload
                :action="uploadAction"
                list-type="picture-card"
                :limit="1"
                :file-list="logoFileList"
                :headers="uploadHeaders"
                :on-success="onLogoUploadSuccess"
                :on-remove="onLogoUploadRemove"
                :on-error="onLogoUploadError"
                :before-upload="onBeforeUpload"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <div class="el-upload__tip" slot="tip">仅支持图片，大小≤5MB</div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="网站简介" prop="webIntroduction">
              <el-input type="textarea" :rows="3" v-model="form.webIntroduction" placeholder="请输入网站简介"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司简介" prop="companyIntroduction">
              <el-input type="textarea" :rows="3" v-model="form.companyIntroduction" placeholder="请输入公司简介"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="页脚内容" prop="footerContent">
              <el-input type="textarea" :rows="3" v-model="form.footerContent" placeholder="请输入页脚内容"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关于我们" prop="about">
              <el-input type="textarea" :rows="3" v-model="form.about" placeholder="请输入关于我们内容"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="帮助中心文档" prop="helpDocsId">
              <el-select v-model="form.helpDocsId" placeholder="请选择帮助中心文档" clearable>
                <el-option
                  v-for="item in docsOptions"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
        </el-form>
      </el-card>

      <!-- 腾讯云短信配置 -->
      <el-card shadow="never">
        <div slot="header">腾讯云短信配置</div>
        <el-form ref="smsFormRef" :model="smsForm" :rules="smsRules" label-width="120px" label-position="left">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="短信应用ID" prop="sdkAppId">
                <el-input v-model="smsForm.sdkAppId" placeholder="请输入短信应用ID" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="短信签名" prop="signName">
                <el-input v-model="smsForm.signName" placeholder="请输入短信签名" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="模板ID" prop="templateId">
                <el-input v-model="smsForm.templateId" placeholder="请输入模板ID" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="secretId" prop="secretId">
                <el-input v-model="smsForm.secretId" placeholder="请输入 secretId" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="secretKey" prop="secretKey">
                <el-input v-model="smsForm.secretKey" placeholder="请输入 secretKey" show-password />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item>
            <el-button type="primary" @click="submitSmsForm">保存</el-button>
            <el-button @click="resetSms">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
  </div>
</template>

<script>
import { getSiteInfo, saveSiteInfo, getSmsInfo, saveSmsInfo } from "@/api/official/site"
import { viewFile } from "@/api/system/file"
import { getToken } from "@/utils/auth"
import { listDocs } from "@/api/official/docs"

export default {
  name: "SiteConfig",
  data() {
    return {
      form: {},
      // 文档选项
      docsOptions: [],
      rules: {
        webTitle: [ { required: true, message: '网站标题不能为空', trigger: 'blur' } ],
        email: [ { required: true, message: '邮箱不能为空', trigger: 'blur' } ],
        phone: [ { required: true, message: '电话不能为空', trigger: 'blur' } ],
        address: [ { required: true, message: '联系地址不能为空', trigger: 'blur' } ],
        webLogoFileId: [ { required: true, message: '请上传网站Logo', trigger: 'change' } ]
      },
      uploadAction: process.env.VUE_APP_BASE_API + '/system/file/upload',
      uploadHeaders: { Authorization: 'Bearer ' + getToken() },
      logoFileList: [],
      // 短信表单
      smsForm: {
        sdkAppId: undefined,
        signName: undefined,
        templateId: undefined,
        secretId: undefined,
        secretKey: undefined
      },
      smsRules: {
        sdkAppId: [{ required: true, message: '短信应用ID不能为空', trigger: 'blur' }],
        signName: [{ required: true, message: '短信签名不能为空', trigger: 'blur' }],
        templateId: [{ required: true, message: '模板ID不能为空', trigger: 'blur' }],
        secretId: [{ required: true, message: 'secretId不能为空', trigger: 'blur' }],
        secretKey: [{ required: true, message: 'secretKey不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.loadInfo()
    this.loadSmsInfo()
    this.loadDocsOptions()
  },
  methods: {
    loadInfo() {
      getSiteInfo().then(res => {
        const data = res && res.data ? res.data : {}
        this.form = Object.assign({
          webLogoFileId: undefined,
          webTitle: undefined,
          webIntroduction: undefined,
          icp: undefined,
          email: undefined,
          phone: undefined,
          address: undefined,
          companyIntroduction: undefined,
          footerContent: undefined,
          about: undefined,
          helpDocsId: undefined
        }, data)
        // 预览 logo
        this.logoFileList = []
        if (this.form.webLogoFileId) {
          viewFile(this.form.webLogoFileId).then(r => {
            if (r && r.data) {
              this.logoFileList = [{ name: r.data.originalName || 'logo', url: r.data.fullPath, uid: r.data.id }]
            }
          }).catch(() => {})
        }
      })
    },
    loadSmsInfo() {
      getSmsInfo().then(res => {
        const data = res && res.data ? res.data : {}
        this.smsForm = Object.assign({
          sdkAppId: undefined,
          signName: undefined,
          templateId: undefined,
          secretId: undefined,
          secretKey: undefined
        }, data)
      })
    },
    /** 加载文档选项 */
    loadDocsOptions() {
      listDocs({pageNum: 1, pageSize: 99999}).then(res => {
        this.docsOptions = res.rows || []
      })
    },
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (!valid) return
        const payload = {
          webLogoFileId: this.form.webLogoFileId,
          webTitle: this.form.webTitle,
          webIntroduction: this.form.webIntroduction,
          icp: this.form.icp,
          email: this.form.email,
          phone: this.form.phone,
          address: this.form.address,
          companyIntroduction: this.form.companyIntroduction,
          footerContent: this.form.footerContent,
          about: this.form.about,
          helpDocsId: this.form.helpDocsId
        }
        saveSiteInfo(payload).then(() => {
          this.$modal.msgSuccess('保存成功')
          this.loadInfo()
        }).catch(err => {
          console.error('save site error', err)
          this.$modal.msgError(err && err.message ? err.message : '保存失败')
        })
      })
    },
    submitSmsForm() {
      this.$refs['smsFormRef'].validate(valid => {
        if (!valid) return
        const payload = {
          sdkAppId: this.smsForm.sdkAppId,
          signName: this.smsForm.signName,
          templateId: this.smsForm.templateId,
          secretId: this.smsForm.secretId,
          secretKey: this.smsForm.secretKey
        }
        saveSmsInfo(payload).then(() => {
          this.$modal.msgSuccess('保存成功')
          this.loadSmsInfo()
        }).catch(err => {
          console.error('save sms error', err)
          this.$modal.msgError(err && err.message ? err.message : '保存失败')
        })
      })
    },
    reset() {
      this.$refs['form'] && this.$refs['form'].resetFields()
      this.logoFileList = []
    },
    resetSms() {
      this.$refs['smsFormRef'] && this.$refs['smsFormRef'].resetFields()
    },
    onBeforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isImage) this.$modal.msgError('仅支持图片文件')
      if (!isLt5M) this.$modal.msgError('图片大小不能超过5MB')
      return isImage && isLt5M
    },
    onLogoUploadSuccess(res) {
      if (res && res.code === 200 && res.data) {
        this.form.webLogoFileId = res.data.id
      } else {
        this.$modal.msgError(res && res.msg ? res.msg : '上传失败')
      }
    },
    onLogoUploadError() {
      this.$modal.msgError('上传失败，请重试')
    },
    onLogoUploadRemove() {
      this.form.webLogoFileId = undefined
    }
  }
}
</script>

<style scoped>
</style>
